<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Sku as SkuService;
class SkuStock extends Admin
{

    public function initialize() {
    	parent::initialize();
    }

    /**
     *成衣sku及库存列表
     * @return string|json
     */
    public function index(){
        $factoryKV = getFactoryKV(false);
        $action = $this->request->param("action");
        if ($action == 'UpToMes') {
            $upMesRet = $this->_stockUpToMes();
            $this->addOrderLog('11000', 10000, '更新 推送mes尾货数'.json_encode($upMesRet));
            return json($upMesRet);
        }
        if ($this->request->isAjax()|| $this->request->param('export')) {
            // 获取分页参数
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $export     = $this->request->param('export/d', 0);
            $factoryId   = $this->request->param('factory_id/d', 0);
            $client_ordernum   = $this->request->param('client_ordernum', '');
            $sku = $this->request->param('sku', '');
            $stock_stop_update=$this->request->param('over_time_range');
            $factoryIdarr=array_keys($factoryKV);
            $where[] = ['stock.factory_id','in',$factoryIdarr];
            if(empty($sku) && empty($client_ordernum)){ //搜特定sku或订单号时,为0的库存也显示
                $where[] = ['available_count','>',0];
            }
            if ($export) {
                set_time_limit(0);
                $page = 1;$limit = 99999;
            }
            if($sku) $where[] = ['stock.sku', '=', $sku];
            if($client_ordernum) $where[] = ['stock.client_ordernum', '=', $client_ordernum];
            if($stock_stop_update) $where[] = ['stock.update_time', '<=', strtotime($stock_stop_update." 23:59:59")];
            if($factoryId) $where[] = ['stock.factory_id', '=', $factoryId];
            $total = db('sku_stock stock')->join('sku sk', 'stock.sku = sk.sku','left')->where($where)->group('stock.sku')->count(1);
            $list = db('sku_stock stock')->join('sku sk', 'stock.sku = sk.sku','left')
                //->join('sku_stock_mes stockmes', 'stock.sku = stockmes.sku','left')
                ->where($where)->page($page)
                ->field("stock.*,sum(stock.available_count) as available_count,sum(defective_count) as defective_count,sk.pic,sk.price")
                ->group('stock.sku')->limit($limit)->order('stock.update_time desc')->select();
            if($total>0){
                $sku_id_arr=array_column($list,'sku');
                $sku_stocklist=db("sku_stock")->where([['sku','in',$sku_id_arr]])
                    ->field("sku,size_name,available_count,sum(available_count) as size_count,defective_count,sum(defective_count) as defective_size_count,
                    stock_position,factory_id,defective_reason,client_ordernum")->group('sku,size_name')->select();
                $orderFrom = [0 => ''] + config('mimo.order_from');
                $xinyin_accounts=db('order')->where([['client_ordernum','in',array_column($sku_stocklist,'client_ordernum')]])->column('is_auto_import,sku','client_ordernum');
                $sku_index_arr=[];
                foreach ($sku_stocklist as $stockval){
                    @$stockval['factory']=$factoryKV[$stockval['factory_id']];
                    $stockval['account']=isset($orderFrom[$xinyin_accounts[$stockval['client_ordernum']]['is_auto_import']]) ? $orderFrom[$xinyin_accounts[$stockval['client_ordernum']]['is_auto_import']] :'';
                    $sku_index_arr[$stockval['sku']][]=$stockval;
                }
                foreach($list as &$sku_stock){
                    $mes_stock=db('sku_stock_mes')->where([['sku','=',$sku_stock['sku']]])->find();
                    $sku_stock['mes_count']=empty($mes_stock['mes_count']) ? '' : $mes_stock['mes_count'];
                    $sku_stock['mes_detail']=empty($mes_stock['mes_detail']) ? '' : $mes_stock['mes_detail'];
                    $sku_stock['mes_date']=empty($mes_stock['update_time']) ? '' : $mes_stock['update_time'];
                    $sku_stock['factory_stock']=$sku_index_arr[$sku_stock['sku']];
                    $sku_stock['all_stock']=array_sum(array_column($sku_index_arr[$sku_stock['sku']],'size_count'));
                }
            }
            $totaldata= db('sku_stock stock')->where($where)
                ->field('sum(available_count) as available_count,sum(defective_count) as defective_count,sum(defective_count*sk.price) as defective_total_price,sum(available_count*sk.price) as total_price')
                ->join('sku sk', 'stock.sku = sk.sku','left')->where($where)->find();
            $data = [];
            $data['totaldata']=$totaldata;
            $data['data'] = $list;
            if ($export) {//导出
                $this->exportSkuStockXls('成衣库存列表-' .date('YmdHis'), $data['data']);
                exit;
            }
            $data['count'] = $total;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $assign = [
            'factoryKV' => ['' => '请选择'] + $factoryKV
        ];
        return $this->assign($assign)->fetch();
    }

    //尾部库存更新至mes
    private function _stockUpToMes(){
        $sku= $this->request->param('sku', 0);
        $ret=(new SkuService())->skuStockUptoMes($sku);
        return $ret;
    }

    /**
     * @author sparkguo
     * 异常库存信息的删除
     */
    public function delStock(){
        $delsku   = $this->request->param('sku', 0);
        if(empty($delsku)) {
            $this->error('请选择要删除的库存信息');
        }
        try {
            db()->startTrans();
            db('sku_stock')->where('sku', 'in', $delsku)->delete();
            db('sku_stock_log')->where('sku', 'in', $delsku)->delete();
            db()->commit();
            return $this->Json(1);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    //成品统计
    public function statistics(){
        $factoryKV = getFactoryKV(false);
        $groupKV = getGroupKV(0);
        $overDateRange    = $this->request->param('over_date_range/s');

        list($startTime, $endTime) = $overDateRange != '' ? array_map('strtotime', explode('~', $overDateRange))
            : [strtotime(date("Y-m-01 00:00:00",strtotime("-3 month"))),time()];//strtotime(date("Y-m-t",strtotime('-1 month')))
        if ($this->request->isAjax()|| $this->request->param('export')) {
            // 获取分页参数
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $factoryId   = $this->request->param('factory_id/d', '');
            $where[] = ['status', 'in', [0,1,2]];
            $where[] = ['chejian_status', '=', 1];
            $where[] = ['o.factory_id', '>', 0];//筛掉未选择工厂的订单
            if($factoryId!==''){
                $where[] = ['o.factory_id', 'eq', $factoryId];
            }
            $where[] = ['tail_over_time', 'between', [$startTime, $endTime+86399]];
            $whereor["o.delivery_status"]=['eq',8];
            $whereor["order_finish.join_finish_state"]=['eq',1];
            $searchWhere=$where;
            if($factoryId!==''){
                $searchWhere[] = ['order_size.factory_id', '>', 0];
            }

            //ordersize表计算裁数/车间数/出货数  ,o.factory_id as ofactory_id
            $finishClothesCountList=db('order o')->field("o.*,FROM_UNIXTIME(tail_over_time,'%Y-%m') as month,sum(sew_cut_count) as sew_cut_count, sum(jiaohuo_tail_count) as jiaohuo_tail_count,sum(order_size.store_count) as store_count,
                sum(order_count) as order_count,sum(shicai_count) as shicai_count,sum(jiaohuo_count) as jiaohuo_count,sum(daohuo_count) as daohuo_count,order_size.factory_id as factory_id,o.factory_id as ofactory_id")
                ->join('order_size order_size', 'order_size.order_id =o.id','inner')
                ->join('order_finish order_finish', 'order_finish.order_id =o.id','left')
                ->where(function ($q) use($whereor){$q->whereOr($whereor);})->where("order_size.factory_id > 0")
                ->where($searchWhere)->group("order_size.factory_id,FROM_UNIXTIME(tail_over_time,'%Y-%m')")->page($page)->limit($limit)->order('tail_over_time desc')->select();

            //order表统计入仓数
            $orderCountList = db('order o')
                ->join('order_finish order_finish', 'order_finish.order_id =o.id','left')
                ->field("o.*,FROM_UNIXTIME(tail_over_time,'%Y-%m') as month,o.factory_id as factory_id,sum(o.store_count) as store_count,sum(confiscate) as mes_confiscate")
                ->where(function ($q) use($whereor){$q->whereOr($whereor);})
                ->where($where)->group("factory_id,FROM_UNIXTIME(tail_over_time,'%Y-%m')")->page($page)->limit($limit)->order('tail_over_time desc')->select();
            $orderStoreCountList=[];
            foreach ($orderCountList as $key=>$item){ //工厂月份所有入仓数数据
                $orderStoreCountList[$item['factory_id'].'_'.$item['month']]=$item;
            }
            //计入统计订单数
            $orderCountList=db('order o')
                ->join('order_finish order_finish', 'order_finish.order_id =o.id','left')
                ->field("count(o.id) as order_count,FROM_UNIXTIME(tail_over_time,'%Y-%m') as month,factory_id")
                ->where(function ($q) use($whereor){$q->whereOr($whereor);})
                ->where($where)->group("factory_id,FROM_UNIXTIME(tail_over_time,'%Y-%m')")->select();//->page($page)->limit($limit)
            $finishOrderCountList=[];
            foreach ($orderCountList as $key=>$item){
                $finishOrderCountList[$item['factory_id'].'_'.$item['month']]=$item;
            }
            //对应月尾完订单统计
            $tailOrderList=db('order o')
                ->field("count(o.id) as order_count,FROM_UNIXTIME(tail_over_time,'%Y-%m') as month,factory_id")
                ->where($where)->group("factory_id,FROM_UNIXTIME(tail_over_time,'%Y-%m')")->select();//->page($page)->limit($limit)
            $orderTailList=[];
            foreach ($tailOrderList as $key=>$item){
                $orderTailList[$item['factory_id'].'_'.$item['month']]=$item;
            }

            //总正品率次品率
            $allFinishTotal=db('order o')->field("o.*,FROM_UNIXTIME(tail_over_time,'%Y-%m') as month,sum(jiaohuo_tail_count) as jiaohuo_tail_count,sum(order_size.store_count) as store_count,
                sum(sew_cut_count) as sew_cut_count,
                sum(order_count) as order_count,sum(shicai_count) as shicai_count,sum(jiaohuo_count) as jiaohuo_count,sum(daohuo_count) as daohuo_count,order_size.factory_id as factory_id")
                ->join('order_size order_size', 'order_size.order_id =o.id','inner')
                ->join('order_finish order_finish', 'order_finish.order_id =o.id','left')
                ->where(function ($q) use($whereor){$q->whereOr($whereor);})
                ->where($searchWhere)->where($where)->find();
            //总入仓数
            $allStoreCount=db('order o')
                ->join('order_finish order_finish', 'order_finish.order_id =o.id','left')
                ->field("FROM_UNIXTIME(tail_over_time,'%Y-%m') as month,o.factory_id as factory_id,sum(o.store_count) as store_count,sum(confiscate) as confiscate")
                ->where(function ($q) use($whereor){$q->whereOr($whereor);})
                ->where($where)->find();


            $total=db('order o')->field("*,FROM_UNIXTIME(tail_over_time,'%Y-%m') as month")->where($where)->group("factory_id,FROM_UNIXTIME(tail_over_time,'%Y-%m')")->count(1);
            //总入库数
            $skuStock=db("sku_stock_log log")->join('order o', 'log.client_ordernum =o.client_ordernum','inner')
                ->field("sum(case when action_type = 1 then available_count else 0 end) as available_checkin_count,
                sum(case when action_type = 2 then available_count else 0 end) as available_checkout_count,
                sum(defective_count) as defective_checkin_count,FROM_UNIXTIME(tail_over_time,'%Y-%m') as month,log.factory_id")
                ->join('order_finish order_finish', 'order_finish.order_id =o.id','left')
                ->where(function ($q) use($whereor){$q->whereOr($whereor);})
                ->where($where)->where('action_type','=',1)->group("log.factory_id,FROM_UNIXTIME(tail_over_time,'%Y-%m')")->order('tail_over_time desc')->select();
            //总出库数
            $skuCheckOutStock=db("sku_stock_log log")->join('order o', 'log.out_ordernum =o.client_ordernum','inner')
                ->field("sum(available_count) as available_checkout_count,log.out_ordernum,log.client_ordernum,FROM_UNIXTIME(tail_over_time,'%Y-%m') as month,log.factory_id")
                ->join('order_finish order_finish', 'order_finish.order_id =o.id','left')
                ->where(function ($q) use($whereor){$q->whereOr($whereor);})
                ->where($where)->where('action_type','eq',2)->group("log.factory_id,FROM_UNIXTIME(tail_over_time,'%Y-%m')")->select();
            $avaribleTotal=$allStoreCount['store_count']+array_sum(array_column($skuStock,'available_checkin_count'))-array_sum(array_column($skuCheckOutStock,'available_checkout_count'));
            $logdata='checkincount:'. array_sum(array_column($skuStock,'available_checkin_count'))."checkoutcount:".array_sum(array_column($skuCheckOutStock,'available_checkout_count')).'shicaicount:'.$allFinishTotal['shicai_count'].'end';
            //$this->addOrderLog(20111, '', $logdata);
            $avaribleTotalPer=$allFinishTotal['shicai_count']>0 ? round($avaribleTotal/($allFinishTotal['shicai_count']+$allFinishTotal['sew_cut_count']),4) :0;
            $defectiveTotal=+array_sum(array_column($skuStock,'defective_checkin_count'));
            $defectiveTotalPer=$allFinishTotal['shicai_count']>0 ? sprintf('%.4f', $defectiveTotal/ ($allFinishTotal['shicai_count']+$allFinishTotal['sew_cut_count']))*100:0;
            //总报废率 1-(MES入仓+没收件数+米莫入库数+次品数)/(裁床件数+补片数)
            $allSscrapPre=$allFinishTotal['shicai_count']>0 ? sprintf('%.2f',
                (1 - (($allStoreCount['store_count'] +$allStoreCount['confiscate']+array_sum(array_column($skuStock,'available_checkin_count'))) / ($allFinishTotal['shicai_count']+$allFinishTotal['sew_cut_count']))) * 100) : 0.00;
            $factoryStock=[];
            foreach ($skuStock as $key=>$stock){
                $factoryStock[$stock['factory_id'].'_'.$stock['month']]=$stock;
            }
            $factoryOutStock=[];
            foreach ($skuCheckOutStock as $key=>$stock){
                $factoryOutStock[$stock['factory_id'].'_'.$stock['month']]=$stock;
            }
            $endtimeStr=date("Y-m-d",$endTime);
            foreach ($finishClothesCountList as $key=>&$item){
                $factorySkuStock=200000;//工厂可出库库存  待计算
                $item['tail_order_count']=isset($orderTailList[$item['factory_id'].'_'.$item['month']]) ? $orderTailList[$item['factory_id'].'_'.$item['month']]['order_count'] : '--';
                $item['finish_order_count']=isset($finishOrderCountList[$item['factory_id'].'_'.$item['month']]) ? $finishOrderCountList[$item['factory_id'].'_'.$item['month']]['order_count'] : '--';
                $item['store_count']=isset($orderStoreCountList[$item['factory_id'].'_'.$item['month']]) ? $orderStoreCountList[$item['factory_id'].'_'.$item['month']]['store_count'] : $item['store_count'] ;
                $current_endtimeStr=date('Y-m-t',$item['tail_over_time'])>= $endtimeStr ? $endtimeStr : date('Y-m-t',$item['tail_over_time']);
                $item['over_date_range']=date("Y-m-01",$item['tail_over_time']).'~'.$current_endtimeStr;
                $item['can_checkout_stock']= $factorySkuStock< round($item['order_count']*0.3) ? $factorySkuStock : round($item['order_count']*0.3);
                $item['mes_checkin_diff_pre']=$item['daohuo_count'] > 0? sprintf('%.4f',$item['store_count']/$item['daohuo_count']) * 100 .'%' : "0.00%";
                $item['shicai_count_diff_pre']=$item['shicai_count'] > 0? sprintf('%.4f',1-$item['store_count']/$item['shicai_count']) * 100 .'%' : "0.00%";

                if(isset($factoryStock[$item['factory_id'].'_'.$item['month']])){
                    $item=array_merge($item,$factoryStock[$item['factory_id'].'_'.$item['month']]);
                }else{
                    $item['available_checkin_count'] = 0;
                    $item['defective_checkin_count'] = 0;
                }
                //mes没收数
                $item['mes_confiscate_count']=!empty($orderStoreCountList[$item['factory_id'].'_'.$item['month']]['mes_confiscate']) ? $orderStoreCountList[$item['factory_id'].'_'.$item['month']]['mes_confiscate'] : 0 ;
                $item['available_checkout_count'] = isset($factoryOutStock[$item['factory_id'].'_'.$item['month']]) ? $factoryOutStock[$item['factory_id'].'_'.$item['month']]['available_checkout_count'] : 0;
                $item['available_pre']=$item['shicai_count'] > 0? sprintf('%.4f',($item['store_count']+$item['available_checkin_count']-$item['available_checkout_count'])/($item['shicai_count']+$item['sew_cut_count'])) * 100: 0.00;
                $item['defective_pre']=$item['shicai_count']>0 ? sprintf('%.2f', ($item['defective_checkin_count'] / $item['shicai_count']) * 100) : 0.00;
                $item['scrap_pre']=$item['shicai_count']>0 ? sprintf('%.2f',
                    (1 - (($item['store_count'] + $item['defective_checkin_count'] +$item['mes_confiscate_count']+ $item['available_checkin_count']) / ($item['shicai_count']+$item['sew_cut_count']))) * 100) : 0.00;
                $item['available_pre'].='%';$item['defective_pre'].='%';
            }
            $data['avaribleTotalPer']=round($avaribleTotalPer*100,2);
            $data['defectiveTotalPer']=$defectiveTotalPer;
            $data['allSscrapPre']=$allSscrapPre;
            $data['data'] = $finishClothesCountList;
            $data['count'] = $total;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $searchdate=[
            '',date("Y-m-01"),date("Y-m-d"),date("Y-m-01",strtotime('-1 month')),date("Y-m-t",strtotime('-1 month')),
             date("Y-m-01",strtotime('-3 month')),date("Y-m-d"),
                 date("Y-m-01",strtotime('-6 month')),date("Y-m-d")
        ];
        $assign = [
            'searchdate'=>$searchdate,
            'overtime_range'=>date("Y-m-d",$startTime).' ~ '.date('Y-m-d',$endTime),
            'clientStatus' => config('mimo.client_status'),
            'factoryKV' => [''=>'请选择',0 => '--未选择--'] + $factoryKV,
            'groupKV' => $groupKV
        ];
        return $this->assign($assign)->fetch();
    }

    //成品统计详情
    public function statisticsDetail(){
        $factoryKV = getFactoryKV(false);
        $groupKV = getGroupKV(0);
        $overDateRange    = $this->request->param('over_date_range/s');
        $factoryId   = $this->request->param('factory_id/d', '');
        list($startTime, $endTime) = $overDateRange != '' ? array_map('strtotime', explode('~', $overDateRange)) : [strtotime(date("Y-m-01 00:00:00",strtotime("-6 month"))),time()];
        if ($this->request->isAjax()|| $this->request->param('export')) {
            // 获取分页参数
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $client_ordernum=$this->request->param('client_ordernum', '');
            $sku=$this->request->param('sku', '');
            $where[] = ['o.tail_over_time', 'between', [$startTime, $endTime+86399]];
            if($client_ordernum) $where[] = ['o.client_ordernum', '=', $client_ordernum];
            if($sku) $where[] = ['o.sku', '=', $sku];
            if($factoryId!==''){
                $where[] = ['o.factory_id', 'eq', $factoryId];
            }
            $whereor["o.delivery_status"]=['eq',8];
            $whereor["order_finish.join_finish_state"]=['eq',1];
            $searchWhere=$where;
            if($factoryId!==''){
                $searchWhere[] = ['order_size.factory_id', '>', 0];
            }
            $finishClothesCountList=db('order o')->field("o.*,FROM_UNIXTIME(tail_over_time,'%Y-%m') as month,sum(jiaohuo_tail_count) as jiaohuo_tail_count,sum(sew_cut_count) as sew_cut_count,sum(order_size.store_count) as astore_count,
                sum(order_count) as order_count,sum(shicai_count) as shicai_count,sum(jiaohuo_count) as jiaohuo_count,sum(daohuo_count) as daohuo_count,sk.pic
                ,o.confiscate")
                ->join('order_size order_size', 'order_size.order_id =o.id','inner')
                ->join('sku sk', 'o.sku = sk.sku','left')
                ->join('order_finish order_finish', 'order_finish.order_id =o.id','left')
                ->where(function ($q) use($whereor){$q->whereOr($whereor);})
                ->where($searchWhere)->group("order_size.order_id")->page($page)->limit($limit)->order('tail_over_time desc')->select();

            $total=db('order o')->field("*")
                ->join('order_finish order_finish', 'order_finish.order_id =o.id','left')
                ->where(function ($q) use($whereor){$q->whereOr($whereor);})->where($where)->count(1);
            //入库数统计
            $skuStock=db("sku_stock_log log")->join('order o', 'log.client_ordernum =o.client_ordernum','inner')
                ->field("sum(available_count) as available_checkin_count,
                sum(defective_count) as defective_checkin_count,FROM_UNIXTIME(tail_over_time,'%Y-%m') as month,log.factory_id,log.client_ordernum")
                ->where($where)->where('action_type','eq',1)->group("log.client_ordernum")->order('tail_over_time desc')->select();
            //出库数统计
            $skuCheckOutStock=db("sku_stock_log log")->join('order o', 'log.out_ordernum =o.client_ordernum','inner')
                ->field("sum(available_count) as available_checkout_count,log.out_ordernum,log.client_ordernum")
                ->where($where)->where('action_type','eq',2)->group("log.out_ordernum")->order('tail_over_time desc')->select();
            //订单sku可出货数
            $statisticsSkuStock=db("sku_stock stock")
                ->field("sum(available_count) as available_count,stock.factory_id,stock.sku")
                ->where([['sku', 'in', array_column($finishClothesCountList,'sku')],['factory_id','=',$factoryId]])->group("stock.sku")->select();
            $newStatisticsSkuStock=[];
            foreach ($statisticsSkuStock as $key=>$stock){
                $newStatisticsSkuStock[$stock['sku']]=$stock;
            }
            $factoryStock=[]; //入库数据
            $factoryOutStock=[]; //出库数据
            foreach ($skuStock as $key=>$stock){
                $factoryStock[$stock['client_ordernum']]=$stock;
            }
            foreach ($skuCheckOutStock as $key=>$stock){
                $factoryOutStock[$stock['out_ordernum']]=$stock;
            }
            foreach ($finishClothesCountList as $key=>&$item){
                $can_checkout_stock=isset($newStatisticsSkuStock[$item['sku']])?$newStatisticsSkuStock[$item['sku']]['available_count']:0;
                $item['can_checkout_stock']=$can_checkout_stock<round($item['order_count']*0.3)?$can_checkout_stock: round($item['order_count']*0.3); //可出货数
                $item['mes_checkin_diff_pre']=$item['daohuo_count'] > 0? sprintf('%.4f',$item['store_count']/$item['daohuo_count']) * 100 .'%' : "0.00%"; //入仓差率(入仓/出货)
                $item['shicai_count_diff_pre']=$item['shicai_count'] > 0? sprintf('%.4f',1-$item['store_count']/$item['shicai_count']) * 100 .'%' : "0.00%"; //入仓/裁剪差异

                if(isset($factoryStock[$item['client_ordernum']])){
                    $item=array_merge($item,$factoryStock[$item['client_ordernum']]);
                }else{
                    $item['available_checkin_count'] = 0;
                    $item['defective_checkin_count'] = 0;
                }
                $item['available_checkout_count'] = isset($factoryOutStock[$item['client_ordernum']]) ? $factoryOutStock[$item['client_ordernum']]['available_checkout_count'] : 0;

                $item['available_pre']=$item['shicai_count'] > 0? sprintf('%.4f',($item['store_count']+$item['available_checkin_count']-$item['available_checkout_count'])/($item['shicai_count']+$item['sew_cut_count'])) * 100: 0.00;
                $item['defective_pre'] = $item['shicai_count'] > 0 ? sprintf('%.4f',  $item['defective_checkin_count'] /($item['shicai_count']+$item['sew_cut_count'])) * 100 : 0.00;
                $item['scrap_pre']=$item['shicai_count']>0 ? sprintf('%.2f',
                    (1 - (($item['store_count'] + $item['defective_checkin_count'] +$item['confiscate']+ $item['available_checkin_count']) / ($item['shicai_count']+$item['sew_cut_count']))) * 100) : 0.00;
                $item['available_pre'].='%';$item['defective_pre'].='%';
            }
            $data['data'] = $finishClothesCountList;
            $data['count'] = $total;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $assign = [
            'overtime_range'=>date("Y-m-d",$startTime).' ~ '.date('Y-m-d',$endTime),
            'clientStatus' => config('mimo.client_status'),
            'factoryKV' => [''=>'请选择',0 => '--未选择--'] + $factoryKV,
            'factoryId'=>$factoryId,
            'groupKV' => $groupKV
        ];
        return $this->assign($assign)->fetch();
    }

    public function updateLogData(){
        $loglist=db('user_process')->order('id desc')->select();
        $where[]=['action_type','in',[2]];
        $where[]=['remark','neq',''];
        foreach ($loglist as $key=>&$item){
            //$item['bar_number']=$item['zhahao'];
            //$item['order_number']=$item['client_ordernum'];
            //unset($item['client_ordernum']);
            unset($item['update_time']); //update_time create_time，id
            unset($item['create_time']);
            unset($item['id']);
        }
        echo json_encode($loglist);
    }

    /**
     * 成衣库存明细
     * @return string|json
     * @author sparkguo
     */
    public function skuStockLog(){
        $search_param=$this->request->param();
        $page       = $this->request->param('page/d', 1);
        $limit      = $this->request->param('limit/d', 20);
        $export     = $this->request->param('export/d', 0);
        $search_param['showtype']=$this->request->param('showtype');
        $factoryId   = $this->request->param('factory_id/d', 0);
        $search_param['sku']=$this->request->param('sku','');
        $stock_stop_update=$this->request->param('over_time_range');
        $client_ordernum=$this->request->param('client_ordernum');
        $stock_action=$this->request->param('action');

        $factoryKV = getFactoryKV(false);
        $factoryIdarr=array_keys($factoryKV);
        $where[] = ['factory_id','in',$factoryIdarr];
        if(!empty($search_param['sku'])){
            $where[] = ['sku', 'like',$search_param['sku']."%"];
        }
         if($stock_stop_update) $where[] = ['create_time', '<=', strtotime($stock_stop_update." 23:59:59")];
        if($factoryId) $where[] = ['factory_id', '=', $factoryId];
        if($client_ordernum) $where[] = ['client_ordernum', '=', $client_ordernum];
        if($stock_action) $where[] = ['action_type', '=', $stock_action];
        $actiontype=['','入库','出库','盘点'];
        if ($this->request->isAjax()|| $this->request->param('export')) {
            $systemUserKV = getSystemUserKV(null);
            $total=db('sku_stock_log stlog')->where($where)->count(1);
            $dataorderval=$search_param['showtype']=='only_one_sku'?"factory_id desc,create_time desc":'create_time desc';
            $stock_log_list = db('sku_stock_log stlog')->where($where)->page($page)->field("*")->limit($limit)->order($dataorderval)->select();
            if($total>0){
                $sku_id_arr=array_column($stock_log_list,'sku');
                $sku_pic_list=db("sku")->where([['sku','in',$sku_id_arr]])->field("pic,sku")->select();
                $sku_index_arr=array_column($sku_pic_list,'pic','sku');
            }
            foreach($stock_log_list as &$logval){
                $logval['available_detail_arr']=json_decode($logval['available_detail']);
                $logval['defective_detail_arr']=json_decode($logval['defective_detail']);
                @$logval['factory_name']=$factoryKV[$logval['factory_id']];
                $logval['action']=$actiontype[$logval['action_type']];
                @$logval['actionuser']=$systemUserKV[$logval['uid']];
                $logval['pic']=$sku_index_arr[$logval['sku']];
            }
            $data = ['data'=>$stock_log_list,'count'=>$total,'code'=>0,'msg'=>'success'];
            if ($export) {//导出
                $this->exportSkuStockXls('成衣库存列表-' .date('YmdHis'), $data['data']);
                exit;
            }
            return json($data);
        }
        $assign = [
            'searchdata'=>$search_param,'factoryKV' => ['' => '请选择'] + $factoryKV,'actionArr'=>['请选择','入库','出库','盘点']
        ];
        return $this->assign($assign)->fetch();
    }

    function exportSkuStockXls($fileName, &$data) {
        $head = ['SKU','生产工厂','所属帐号','最后更新日期','库存总数','尺码库存'];
        $params = [];

        $exportdata = [];
        foreach ($data as $k => $v) {
            $size_countstr='';
            foreach ( $v['factory_stock'] as $key=>$size_stock){
                $size_countstr.=$size_stock['size_name'].":".$size_stock['size_count']."，";
            }
            $exportdata[] = [
                $v['sku'],
                $v['factory_stock'][0]['factory'],
                $v['factory_stock'][0]['account'],
               // "<img src='".$v['pic']."' width='30'>",
                $v['update_time']==0 ? '':date('Y-m-d', $v['update_time']),
                $v['available_count'],
                $size_countstr
            ];
        }
        $params['file'] = $fileName;
        $params['sheet'] = [
            [
                'head' => $head, // 表头
                'data' => $exportdata,
            ],
        ];
        unset($data);
        plugins_run('excel/excel/export', $params);
    }

    //编辑库存
    function StockEdit(){
        $search_param=$this->request->param();
        $factory=$this->request->param('factory_id');
        $savesku=$this->request->param('sku');
        $available=$this->request->param('available');
        $defective=$this->request->param('defective');
        $stock_position=$this->request->param('stock_position');
        $remark=$this->request->param('remark');
        $action=$this->request->param('action');
        $save_type=$this->request->param('save_type');
        $client_ordernum=$this->request->param('client_ordernum');
        $dress_line_code=$this->request->param('dress_line_code');
        $size_name=$this->request->param('size_name');
        $edit_client_ordernum=$this->request->param('edit_client_ordernum');
        if($action=='get_sku_size'){ //获取sku尺码
            $sizedata='';
            if($client_ordernum){
                $ordersku=db('order')->where(['client_ordernum' => $client_ordernum])->field("id,sku,factory_id")->find();
                if($ordersku){
                    $order_size=db('order_size')->where('order_id', $ordersku['id'])->field("factory_id,client_ordernum,size_name")->order('mid asc')->select();
                    $sizedata=['factory'=>$ordersku['factory_id'],'ps_size_name'=>array_column($order_size,'size_name'),'sku'=>$ordersku['sku']];
                }
            }else{
                if($dress_line_code){
                    $stockinfo=db('sku_stock sku_stock')->where([['dress_line_code','like',"%$dress_line_code%"]])->join('sku_stock_log log', "sku_stock.sku=log.sku", 'left')
                        ->field("sku_stock.*,log.client_ordernum")->order('log.create_time desc')->find();
                    if(!empty($stockinfo)){
                        $order_size=db('order_size')->where('client_ordernum', $stockinfo['client_ordernum'])->field("factory_id,client_ordernum,size_name")->order('mid asc')->select();
                        $sizedata=['factory'=>$stockinfo['factory_id'],'ps_size_name'=>array_column($order_size,'size_name'),'sku'=>$stockinfo['sku']];
                    }
                }
            }
            $data=['code'=> 200,'msg'=>'success','data'=>$sizedata];
            if(empty($sizedata)){
                $data['msg']=$client_ordernum.'订单号不存在';
            }else{
                if(!empty($stockinfo)){ //条形码查询
                    $data['data']['factory']=$stockinfo['factory_id'];
                    $sizeval=$stockinfo;
                }else{
                    $data['data']['factory']=$ordersku['factory_id'];
                    $sizeval=db('sku_stock')->where(['sku' => $ordersku['sku'], 'factory_id' => $ordersku['factory_id']])->field("*")->order('create_time desc')->find();
                }
                if(!empty($sizeval)){
                    $sizeval['client_ordernum']=isset($sizeval['client_ordernum'])==''?$client_ordernum:$sizeval['client_ordernum'];
                    $sizeval['av']=json_decode($sizeval['available_detail'],true);
                    $sizeval['de']=json_decode($sizeval['defective_detail'],true);
                    $data['data']['sizeval']=$sizeval;
                }
            }
            return json($data);
            die;
        }
        if(is_array($factory) && count($factory)>0) {
            $factoryKV = getFactoryKV();
            if(!is_array($available[0])){
                return $this->Json(0,'新先编辑尺码库存');die;
            }
            foreach ($factory as $key => $saveinfo) {
                if(!in_array($factory[$key],array_keys($factoryKV))) {
                    return $this->Json(0,'未找到该订单所属工厂，请确认该订单工厂已设置');die;
                }
                $oldstock_info=db('sku_stock')->where(['sku' => $savesku, 'factory_id' => $factory[$key],'client_ordernum'=>$edit_client_ordernum[$key],'size_name'=>$size_name[$key]])->find();
                $actiontime = time();
                $available_detail = json_encode($available[$key]);
                $defective_detail = json_encode($defective[$key]);
                $savedata = ['available_count' => array_sum($available[$key]), 'defective_count' => array_sum($defective[$key]),
                    'stock_position' => $stock_position[$key], 'available_detail' => $available_detail,'dress_line_code'=>$dress_line_code[$key],
                    'defective_detail' => $defective_detail, 'remark' => $remark[$key]];
                $stock_log = ['sku' => $savesku, 'uid' =>ADMIN_ID,'action_type' => 3,'stock_position' => $stock_position[$key],'available_detail' => $available_detail,'defective_detail' => $defective_detail,
                'remark' => $remark[$key],'factory_id' => $factory[$key],'create_time' => $actiontime,'client_ordernum'=>$oldstock_info['client_ordernum']];
                try {
                    db()->startTrans();
                    $savedata['factory_id']=$factory[$key];
                    if($save_type=='add' && !$oldstock_info){//新增成衣库存
                        $savedata['sku']=$savesku;
                        db('sku_stock')->insert($savedata);
                    }else{
                        if($oldstock_info['available_detail']==$savedata['available_detail']){
                            unset($stock_log['available_detail']);//删除无变动的日志
                        }
                        if($oldstock_info['defective_detail']==$savedata['defective_detail'] || $oldstock_info['defective_count']==$savedata['defective_count']){
                            unset($stock_log['defective_detail']);
                        }
                        db('sku_stock')->where(['id'=>$oldstock_info['id']])->update($savedata);
                    }
                    if(isset($stock_log['available_detail']) || isset($stock_log['defective_detail'])){
                        db('sku_stock_log')->insert($stock_log);
                    }
                    db()->commit();
                } catch (\Exception $e) {
                    db()->rollback();
                    return $this->Json(0, '操作失败' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
                }
            }
            $savedata['sku']=$savesku;$savedata['client_ordernum']=$client_ordernum;$savedata['factory_name']=$factoryKV[$savedata['factory_id']];$savedata['date']=date('Y-m-d H:i:s');
            return $this->Json(1,'success',$savedata);
        }

        $factoryKV = getFactoryKV(false);
        $sku=$search_param['sku']=$this->request->param('sku','');
        $assign = [
            'factoryKV' => ['' => '请选择'] + $factoryKV,'sku'=>$sku,'action'=>$action
        ];
        $where = [];
        $visit_factory_ids=array_keys($factoryKV);
        if($sku) $where[] = ['sku', '=', $sku];
        if(count($visit_factory_ids)>0) $where[]=['factory_id','in',$visit_factory_ids];
        $sku_stocklist=db('sku_stock')->where($where)->field("*")->order('create_time desc')->select();
        foreach ($sku_stocklist as &$stockval){
            $stockval['factory']=$factoryKV[$stockval['factory_id']];
            $stockval['available_detail_arr']=empty($stockval['available_detail'])?json_decode($stockval['defective_detail']):json_decode($stockval['available_detail']);
            $stockval['defective_detail_arr']=empty($stockval['defective_detail'])?json_decode($stockval['available_detail']):json_decode($stockval['defective_detail']);
            $sku_index_arr[$stockval['sku']][]=$stockval;
        }
        $assign['stock_list']=$sku_stocklist;
        return $this->assign($assign)->fetch();
    }

    /**
     * 成品统计》订单详细的设置字段
     * @author zhuguosen 905502314@qq.com
     * @date 2022/1/15
     */
    public function editUnit()
    {
        $param = [
            'id' => $this->request->param('id/d', 0),
            'field' => $this->request->param('field/s', 0),
            'value' => $this->request->param('value/s', 0),
        ];
        $temp = db('order')->where([
            ['id', '=', $param['id']],
        ])->update([
            trim($param['field']) => intval($param['value']),
        ]);
        if ($temp == 1) {
            return $this->Json(1, '修改成功', $temp);
        }
        return $this->Json(10, '修改失败', $temp);
    }
}